package com.zhx.common.common.interceptor;

import cn.hutool.extra.servlet.ServletUtil;
import com.zhx.common.common.domain.dto.RequestInfo;
import com.zhx.common.common.util.RequestHolder;
import jdk.nashorn.internal.parser.Token;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;


@Component
public class CollectorInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求属性中获取用户ID
        Long uid = Optional.ofNullable(request.getAttribute(TokenInterceptor.UID))
                // 将属性值转换为字符串
                .map(String::valueOf)
                // 将字符串转换为长整型
                .map(Long::parseLong)
                // 如果没有找到属性值，则返回null
                .orElse(null);

        // 获取客户端IP地址
        String ip = ServletUtil.getClientIP(request);

        // 创建RequestInfo对象，并设置用户ID和IP地址
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setUid(uid);
        requestInfo.setIp(ip);

        // 将RequestInfo对象设置为请求的属性，以便后续使用
        RequestHolder.set(requestInfo);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHolder.remove();
    }
}
